module.exports={
    writeHtmlText:function(response,msg,autoReferenshTime,headers){
        response.setHeader('Content-Type', "text/html;charset=UTF8")
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "token,Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE");
        // response.writeHead(200, {'Content-Type': "application/json"});
        if(headers){
            for(var key in headers){
                response.setHeader(key, headers[key])
            }
        }
        response.writeHead(200);
        if(autoReferenshTime)
            msg='<meta http-equiv="refresh" content="' + autoReferenshTime + '">'+msg;
        response.write(msg);
        response.end();
    },
    /**
     * 预处理微信的请求
     * 排序，签名，转成xml
     */
    preHandlerWeixinReqParam:function(appId,param,api_key){
        param.sort(function (a, b) {
            var index = -1;
            while (true) {
                index++;
                if (a[0].length == index)
                    return -1;
                if (b[0].length == index)
                    return 1;
                if (a[0].charCodeAt(index) == b[0].charCodeAt(index))
                    continue;
                return a[0].charCodeAt(index) - b[0].charCodeAt(index);
            }
        })
        var sign = "";
        for (var i = 0; i < param.length; i++) {
            sign += (i == 0 ? "" : "&") + param[i][0] + "=" + param[i][1];
        }
        sign += "&key=" + api_key
        sign = this.sha1(sign);
        sign = sign.toUpperCase();
        param.push(["sign", sign])
        var data = "<xml>"
        if(appId)
            data += "<appid>" + appId + "</appid>"
        for (var i = 0; i < param.length; i++) {
            data += "<" + param[i][0] + ">" + param[i][1] + "</" + param[i][0] + ">"
        }
        data += "</xml> "
        return data;
    },
    // 微信token认证底层实现
    sha1:function(str) {
        // var crypto=require("crypto");
        // var md5sum = crypto.createHash("sha1");
        // md5sum.update(str);
        // str = md5sum.digest("hex");
        // return str;

        var crypto = require("crypto");
        str = crypto.createHash('md5').update(str).digest('hex')
        return str;
    },
    httpRequestAsync2:async function(url, options, data){
        var self=this;
        return new Promise(function(resolve,reject){
            self.httpRequest2(url,options, data,function(req,data,res){
                resolve({res:true,data:data,response:res,request:req});
            },function(error){
                resolve({ res: false, data:error });
            })
        })
    },
    httpRequestAsync:async function(httpsReq, options, data){
        var self=this;
        return new Promise(function(resolve,reject){
            self.httpRequest(httpsReq,options, data,function(req,data,res){
                resolve({res:true,data:data,response:res,request:req});
            },function(error){
                resolve({ res: false, data:error });
            })
        })
    },
    httpRequest2:function(url,options, data, sucessFun, errorFun){
        if(!options)
            options={method: 'GET'}
        if (!options.headers)
            options.headers = { 'Content-Type': 'application/json' }
        options.headers["Content-Length"] = data?Buffer.byteLength(data):0;
        var httpsReq=url.indexOf("https")==0;
        const https = httpsReq ? require('https'):require('http');
        let handler=function(res){
            let bufferList=[];
            if(!options.isBuffer)
                res.setEncoding('utf-8');
            res.on('data', secCheck => {
                bufferList.push(secCheck)
            });
            res.on('end', () => {
                if (sucessFun) sucessFun(req, options.isBuffer?Buffer.concat(bufferList):bufferList.join(""),res);
            })
            res.on('error', err => {
                if (errorFun) errorFun(err);
            });
        };
        let req=https.request(url,options,handler);
        req.on('error', err => {
            if (errorFun) errorFun(err);
        })
        if (data)
            req.write(data);
        req.end();
    },
    httpRequest:function(httpsReq,options, data, sucessFun, errorFun) {
        var url=httpsReq?"https://":"http://";
        url+=options.hostname;
        if(options.port)
            url+=":"+options.port
        if(options.path)
            url+=options.path;
        this.httpRequest2(url,options, data, sucessFun, errorFun)
    },
    getWebsocketResponse(key){
        var accept=key
        var msg="ok"
        var str="HTTP/1.1 101 OK\r\n"
            +"Access-Control-Allow-Headers:token,content-type\r\n"
            +"Access-Control-Allow-Origin:*\r\n"
            +"Accept-Ranges:none\r\n"
            +"Vary:Accept-Encoding\r\n"
            +"Content-Type:text/html\r\n"
            +"Content-Length:$msgLength\r\n"
            +"Date:$time1\r\n"
            +"Expires:$time2\r\n"
            +"Cache-Control:private,max-age=0\r\n"
            +"Last-Modified:$time3\r\n"
            +"X-Content-Type-Options:nosniff\r\n"
            +"Server:wntd\r\n"
            +"X-XSS-Protection:0\r\n"
            +"Upgrade:websocket\r\n"
            // +"Sec-WebSocket-Protocol:SDF\r\n"
            // +"Sec-WebSocket-Extensions:sdfsfd\r\n"
            // +"Sec-WebSocket-Accept:\r\n"
            // +"Sec-WebSocket-Key:pdht1MjdMucZ8FAGEeMrQg==\r\n"
            +"Connection:Upgrade\r\n"
            +"\r\n$msg"
        var time=new Date();
        str=str.replace("$time1",time.toString())
        str=str.replace("$time2",time.toString())
        str=str.replace("$time3",time.toString())
        str=str.replace("$msgLength",msg.length)
        str=str.replace("$msg",msg)

        return str
    },
    getHttpResponseText(msg){
        var str="HTTP/1.1 200 OK\r\n"
            +"Access-Control-Allow-Headers:token,content-type\r\n"
            +"Access-Control-Allow-Origin:*\r\n"
            +"Accept-Ranges:none\r\n"
            +"Vary:Accept-Encoding\r\n"
            +"Content-Type:text/html\r\n"
            +"Content-Length:$msgLength\r\n"
            +"Date:$time1\r\n"
            +"Expires:$time2\r\n"
            +"Cache-Control:private,max-age=0\r\n"
            +"Last-Modified:$time3\r\n"
            +"X-Content-Type-Options:nosniff\r\n"
            +"Server:wntd\r\n"
            +"X-XSS-Protection:0\r\n"
            +"Connection:keep-alive\r\n"
            +"\r\n$msg"
        var time=new Date();
        str=str.replace("$time1",time.toString())
        str=str.replace("$time2",time.toString())
        str=str.replace("$time3",time.toString())
        str=str.replace("$msgLength",msg.length)
        str=str.replace("$msg",msg)

        return str
    }
}